package com.ting.test.algorithms.查找算法.二分查找;

/**
 * 普通的二分查找算法是以有序数组为前提，在有序的数组中对数据快速查找
 */
public class 二分查找 {
    public static void main(String[] args) {
        int[] arr = new int[]{1, 2, 3, 3, 4, 4, 5, 6, 7, 8, 9, 10};
        int num = func(arr, 9);
        System.out.println(num);
    }

    /**
     * 返回目标数据的下标
     * 没有则返回-1
     *
     * @param arr
     * @param target
     * @return
     */
    private static int func(int[] arr, int target) {
        if (null == arr) {
            return -1;
        }
        int left = 0;
        int mid;
        int right = arr.length - 1;
        while (left < right) {
            mid = (left + right) / 2;
            if (arr[mid] == target) {
                return mid;
            }
            if (arr[mid] > target) {
                right = mid - 1;
            } else {
                left = mid + 1;
            }
        }
        return -1;
    }
}
